﻿//record last location
var fixedfields = [
   { name: 'sssid' },
   { name: 'devicename' },
   { name: 'devicetype' },
   { name: 'gpsavailable', type: 'boolean' },
   { name: 'latitude' },
   { name: 'longitude' },
   { name: 'gpstime' },
   { name: 'receivedtime' },
   { name: 'direction', type: 'string' },
   { name: 'speed' },
   { name: 'altitude' },
   { name: 'devicestate' },
   { name: 'address' },
   { name: 'alarminfo' },
   { name: 'alarmcustomText' },
   { name: 'gsmsignal', type: 'int' },
   { name: 'satellites', type: 'int' },
   { name: 'journey', type: 'int' },
   { name: 'runtime', type: 'int' },
   { name: 'RFID' },
   { name: 'gsmlatitude', type: 'float' },
   { name: 'gsmlongitude', type: 'float' },
   { name: 'gsmaccuracy', type: 'int' },
   { name: 'hasgsmlocation', type: 'boolean' },
   { name: 'baseid' },
   { name: 'lastalarmtime' },
   { name: 'iconname' },
   { name: 'status' },
   { name: 'online', type: 'boolean' },
   { name: 'alarmspeed', type: 'float' },
   { name: 'alarmlatitude', type: 'float' },
   { name: 'alarmlongitude', type: 'float' }
// { name: 'lastgeofenceid', type: 'int' },
   ,{ name: 'lastgeofencename', type: 'string' }
   ,{name:'HDOP'}
//{ name: 'UserDefineList' }
];

function copyArray(ar) {
    var r = [];
    var i;
    for (i = 0; i < ar.length; i++)
        r.push(ar[i]);
    return r;
}
var locationfields = copyArray(fixedfields);

function UserDefineAlarm(alarmtype, expression) {
    this.alarmtype = alarmtype;
    this.expression = expression;
}
var fixfieldslength = locationfields.length; // the fixed fields numbers
var dymanicfieldnames = [];
var dymanicalarminfo = [];

///read user define fields names
function getUserDefineFieldsNames() {
    dymanicfieldnames = [];
    locationfields = copyArray(fixedfields);
    var sfields = [{ name: 'FieldName'}];
    var userdefinefieldsreader = new Ext.data.JsonReader({}, sfields);
    var userdefinefieldsproxy = new Ext.data.HttpProxy({
        url: 'HandlerGetUserDefineFields'
    });
    var userdefinefieldsstore = new Ext.data.Store({
        reader: userdefinefieldsreader,
        proxy: userdefinefieldsproxy
    });

    userdefinefieldsstore.load({
        callback: function() {
            //dymanicfieldnames.clear();
			dymanicfieldnames = [];
            userdefinefieldsstore.each(function(record) {
                var fname = record.get("FieldName");
                dymanicfieldnames.push(fname);
                locationfields.push(new Ext.data.Field({ name: fname }));
            });
        }
    });
}


function getAlarmDefine() {
    dymanicalarminfo = [];
    var afields = [{ name: 'AlarmType' }, { name: 'Expression'}];
    var userdefinealarmreader = new Ext.data.JsonReader({}, afields);
    var userdefinealarmproxy = new Ext.data.HttpProxy({
        url: 'HandlerGetUserDefineAlarm'
    });
    var userdefinealarmstore = new Ext.data.Store({
        reader: userdefinealarmreader,
        proxy: userdefinealarmproxy
    });

    userdefinealarmstore.load({
        callback: function() {
            //dymanicalarminfo.clear();
			dymanicalarminfo = [];
            userdefinealarmstore.each(function(record) {
                var type = record.get("AlarmType");
                var expression = record.get("Expression");
                var ainfo = new UserDefineAlarm(type, expression);
                dymanicalarminfo.push(ainfo);
                
//                devicestore.each(function(dr) {
//                   var alarmstring = dr.get("qtipalarm");
//                   if(alarmstring.length>0){
//                      var alarmtype = getAlarmTypeFromAlarmString(alarmstring);
//                      if(alarmtype == type){
//                        dr.set(qtipalarm,expression);
//                      }
//                   }
//                });
                
            });
            getAndDrawLastLocation(true, false);

        }
    });
}

getAlarmDefine();
getUserDefineFieldsNames();

//add user define fields to fields arrays
/*function addUserDefineFields(fieldsArray) {
var sfields = [ {name:'FieldName'}];
var userdefinefieldsreader = new Ext.data.JsonReader({}, sfields);
var userdefinefieldsproxy = new Ext.data.HttpProxy({
url:'HandlerGetUserDefineFields'
});
var userdefinefieldsstore = new Ext.data.Store({
reader: userdefinefieldsreader,
proxy : userdefinefieldsproxy
});

userdefinefieldsstore.load({
callback: function() {
userdefinefieldsstore.each(function(record) {
var fname = record.get("FieldName");
fieldsArray.push(new Ext.data.Field({ name: fname }));
});
}
});
}*/



var lastlocationintervalsreader = new Ext.data.JsonReader({}, locationfields);

var lastlocationintervalsproxy = new Ext.data.HttpProxy({
    url: 'HandlerLastLocation',
    timeout:30000
});

//last location interval store
var lastlocationintervalstore = new Ext.data.Store({
    reader: lastlocationintervalsreader,
    proxy: lastlocationintervalsproxy

});
/* phu commnent
var onlinestore = new Ext.data.Store({
    reader: new Ext.data.JsonReader({}, [{ name: 'online' }, { name: 'sssid'}]),
    proxy: new Ext.data.HttpProxy({ url: 'HandlerCheckOnline' })
});
*/
function getallsssids() {
    var sssids = "";
    var count = devicestore.getCount();
    var i;
    var nochoose = true;
    for (i = 0; i < count; i++) {
        var record = devicestore.getAt(i);
        var choosed = record.get("choosed");
        var devicetype = record.get("devicetype");

        if (sssids.length == 0) {
            sssids = record.get("sssid");
        }
        else {
            sssids += "|" + record.get("sssid");
        }
    }
    return sssids;
}

function getselectedsssids(){
    var sssids = "";
    var count = devicestore.getCount();
    var i;
    var nochoose = true;
    for (i = 0; i < count; i++) {
        var record = devicestore.getAt(i);
        var choosed = record.get("choosed");
        var devicetype = record.get("devicetype");
        if (choosed) {
            if (sssids.length == 0) {
                sssids = record.get("sssid");
            }
            else {
                sssids += "|" + record.get("sssid");
            }
        }
    }
    return sssids;
}

function getAndDrawLastLocation(refreshalarm, refreshInfo,istimerinterval) {
    if (onlyshowselecteddevice) {
        lastlocationintervalstore.baseParams = { checksssids: getallsssids(), nochecksession: true };
        if (istimerinterval == true) {
            devicestore.each(function(record) {
                var choosed = record.get("choosed");
                if (choosed) {
                }
                else {
                    if(imap!= null){
                       // imap.removeFromMap(record.get("sssid"));
					}
                }
            });
        }
    }
    if (showtrackeronlinestatus) {
		/* phu comment
        onlinestore.load({
            callback: function() {
                onlinestore.each(function(record) {
                    var sssid = record.get("sssid");
                    var devicecount = devicestore.getCount();
                    for (i = 0; i < devicecount; i++) {
                        var drecord = devicestore.getAt(i);
                        var tmpid = drecord.get("sssid");
                        if (tmpid == sssid) {
                            drecord.set("online", record.data['online']);
                        }
                    }
                })
            }
        });
		*/
    }
    lastlocationintervalstore.load({
        // store loading is asynchronous, use a load listener or callback to handle results
        callback: function () {
            if (lastlocationintervalsreader.jsonData.logout != 1) {
                if (showmiles) {
                    lastlocationintervalstore.each(function (record) {
                        record.set('speed', kilos2miles(record.get('speed')));
                    });
                }
                if (Ext.isArray(lastlocationintervalsreader.jsonData)) {
                    var tmpstore = new Ext.data.ArrayStore({
                        fields: locationfields
                    });
                    if (onlyshowselecteddevice) {
                        lastlocationintervalstore.each(function (record) {
                            devicestore.each(function (drec) {
                                if (drec.get("sssid") == record.get("sssid") && (drec.get("choosed"))) {
                                    tmpstore.add(record);
                                }
                            });
                        });
                    }
                    if (imap != null) {

                    	if (onlyshowselecteddevice) {
                    		//imap.drawFromStore(tmpstore);
                    	} else {
                    		//imap.drawFromStore(lastlocationintervalstore);
                    	}

                    }
                    //change devicel list information for new data  
                    lastlocationintervalstore.each(function (record) {
                        var sssid = record.get("sssid");
                        var devicecount = devicestore.getCount();
                        var i;
                        var alarminfo = record.get("alarminfo");
                        var alarmstring = getAlarmStringFromAlarmTypeExtend(alarminfo, sssid);
                        if (alarminfo == "10010" || alarminfo == "10011") {
                            //polygon geofence
                            alarmstring += "(" + record.get("lastgeofencename") + ")";
                        }
                        var alarmtime = record.get("lastalarmtime");
                        var alarmtip = alarmstring + " " + alarmtime;
                        var updatetimechanged = false;

                        for (i = 0; i < devicecount; i++) {
                            var drecord = devicestore.getAt(i);
                            var tmpid = drecord.get("sssid");

                            var alarmaction = 'icon-none';
                            if (hasEmergencyAlarm(alarminfo))
                                alarmaction = 'icon-alarm';
                            if (tmpid == sssid) {
                                //we already change ext.css .x-grid3-dirty-cell to prevent dirty-icon show
                                var lastupdate = drecord.get("lastupdate");
                                var newupdate = record.data["receivedtime"];
                                if (newupdate != lastupdate) {
                                    updatetimechanged = true;
                                    if (g_OTAWindowObject != null)
                                        g_OTAWindowObject.upgradePatch(sssid);
                                    drecord.set("lastupdate", record.data['receivedtime']);

                                    //drecord.set("online", record.data['online']);
                                    drecord.set("status", record.data['status']);
                                    drecord.set("alarminfo", "");
                                    if (myChooseDeviceListRowSSSID == sssid && isOpenExtentFn) {
                                        var mySingleStore = createSingleLocationStore(sssid);
                                        mySingleStore.load({
                                            callback: function () {
                                                mySingleStore.each(function (record) {
                                                    showStatusinPanelByRecord(record);
                                                });
                                            }
                                        });
                                        showStatusinPanelByRecord(record);
                                    }
                                    try {
                                        if (refreshalarm) {
                                            drecord.set("actionalarm", alarmaction);
                                            drecord.set("qtipalarm", alarmtip);
                                        }
                                    }
                                    catch (err) {

                                    }
                                }
                            }
                        }

                        //draw RTT map
                        for (i = 0; i < rtrakingWindows.length; i++) {
                            if (rtrakingWindows[i].deviceID == sssid) {
                                var tmpMap = rtrakingWindows[i].MapObject;
                                tmpMap.realtimeTracking(record, _TrackerMain_GPSTime, _TrackerMain_Speed);
                                //                        var tmpMSBmap = rtrakingWindows[i].MSBMap;
                                //                        tmpMSBmap.realtimeTracking(record, _TrackerMain_GPSTime, _TrackerMain_Speed);
                            }
                        }

                        //if has alarm , add alarm to quickly alarm list
                        if (hasEmergencyAlarm(alarminfo)) {
                            var trackername = record.get("devicename");
                            //var alarmexpression = alarmtip;
                            var updatetime = record.get("receivedtime");
                            //var lati = record.get("latitude");
                            //var longi = record.get("longitude");

                            var alarmtime = record.get("lastalarmtime");
                            var alarmlati = record.get("alarmlatitude");
                            var alarmlongi = record.get("alarmlongitude");
                            var alarmspeed = record.get("alarmspeed");
                            addAlarmtoImmAlarmList(sssid, trackername, alarmtime, alarmlati, alarmlongi, alarmstring, alarmtime, alarmspeed, true);
                        }
                        if (refreshInfo && updatetimechanged) {
                            var timestring = record.get("receivedtime").split(' ');

                            addNewInfoWithTime(record.get("devicename"), timestring[1], _TrackerMain_ReceviedData);
                        }
                        var t;
                        for (t in record.json) {
                            var fname = t;
                            if (fname.indexOf("01") != -1 && fname.length == 4) {
                                if (fname == '01FF') {

                                    if (g_FuelSensorWindowObject != null) {
                                        var v = record.json[t];
                                        g_FuelSensorWindowObject.changeFuelValue(sssid, record.get("receivedtime"), v);
                                    }
                                }
                                else {
                                    if (g_ExtSensorWindowObject != null) {
                                        var v = record.json[t];
                                        var sensornumber = parseInt(fname.substr(2, 2), 16);
                                        g_ExtSensorWindowObject.changeValue(sssid, record.get("receivedtime"), sensornumber, v);
                                    }
                                }
                            }
                        }
                    });
                }

            }
            else {

                //session timeout,ask for redo login
                window.alert(_TrackerMain_SessionTimeout);
                window.location.href = 'Login'
                //window.history.go(-1);
            }
        }
    });
}

function reloadAllLastlocations() {
    devicestore.reload();
    devicestore.each(function(record) {
        var sssid = record.get("sssid");
        var singlelocationstore = createSingleLocationStore(sssid);
        singlelocationstore.load({
            callback: function() {
                if (showmiles){
                    singlelocationstore.each(function(record){
	                    record.set('speed', kilos2miles(record.get('speed')));
                    });
                }
                if (imap != null) {
                    var count = singlelocationstore.getCount();
                    if (count > 0) {
                        //imap.drawFromStore(singlelocationstore, true, null, true);
                    }
                }
            }
        });

    });
}


function reloadSingleLastlocations(trackername) {
    devicestore.reload();
    devicestore.each(function(record) {
        var sssid = record.get("sssid");
        if (trackername == record.get("trackername") && trackername != undefined) {
            var singlelocationstore = createSingleLocationStore(sssid);
            singlelocationstore.load({
                callback: function() {
                    if (showmiles){
                        singlelocationstore.each(function(record){
	                        record.set('speed', kilos2miles(record.get('speed')));
                        });
                    }
                    if (imap != null) {
                        var count = singlelocationstore.getCount();
                        if (count > 0) {
                            //imap.drawFromStore(singlelocationstore, true, null, true);
                        }
                    }
                }
            });
        }
    });
}


window.setInterval('getAndDrawLastLocation(true,true,true)', 20000);

